package com.ygxsk.carhome.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Autuhor:itchen
 * Time:2020/3/16 0016  12:08
 * Description: this is  第二个时间工具类
 */
public class DateUtil {


    /**
     * 获取两个时间之间的天数
     *
     * @param maxDate 大的日期
     * @param minDate 小的日期
     * @return
     * @throws Exception
     */
    public static int getDay(Date maxDate, Date minDate) throws Exception {
        int day = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        minDate = sdf.parse(sdf.format(minDate));
        maxDate = sdf.parse(sdf.format(maxDate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(minDate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(maxDate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        if (between_days > 0) {
            day = Integer.parseInt(String.valueOf(between_days));
        }
        return day;
    }

    /**
     * 由出生日期获得年龄
     *
     * @param birthDay
     * @return
     * @throws Exception
     */
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException("The birthDay is before Now.It's unbelievable!");
        }
        //获取当前年
        int yearNow = cal.get(Calendar.YEAR);
        //获取当前月
        int monthNow = cal.get(Calendar.MONTH);
        //获取当日
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);
        //获取出生那年
        int yearBirth = cal.get(Calendar.YEAR);
        //获取出生月
        int monthBirth = cal.get(Calendar.MONTH);
        //获取出生日
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);
        //年纪
        int age = yearNow - yearBirth;
        //如果现在的月份小于生日的月份,年龄-1,如果等于出生的月份,日前小于生日日期,年龄-1
        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth)
                    age--;
            } else {
                age--;
            }
        }
        return age;
    }

}
